﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data.Common;
using Data.Enum;
using Data.Model;

namespace DataAccess.SystemManage
{
    /// <summary>
    /// 权限管理类
    /// </summary>
    public class SysPrivilege : DbBase, ISysPrivilege
    {
        #region 资源的缓存

        private static ResultInfo<List<string>> _cacheResources=new ResultInfo<List<string>>(){ResultNumber = ResultEnum.Error};

        private static ResultInfo<Dictionary<string, string>> _cacheDicResources=new ResultInfo<Dictionary<string, string>>(){ResultNumber = ResultEnum.Error};

        #endregion


        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="priviName">权限名称</param>
        /// <returns></returns>
        public ResultInfo<PagingDataSet<Privilege>> GetPrivileges(int pageIndex, int pageSize, string priviName)
        {
            var result = new ResultInfo<PagingDataSet<Privilege>>();
            try
            {
                using (SqlCommand myCommand = GetProCommand())
                {
                    myCommand.CommandText = "Common_GetPagingRecords";
                    StringBuilder fromClause = new StringBuilder();
                    fromClause.AppendFormat("Privilege R with (nolock)");

                    StringBuilder whereClause = new StringBuilder();
                    if (!string.IsNullOrEmpty(priviName))
                    {
                        whereClause.Append(string.Format(" and R.privilegename like '%{0}%' ", priviName));
                    }
                    if (whereClause.Length > 3)
                    {
                        whereClause.Remove(0, 5);
                    }

                    myCommand.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex - 1;
                    myCommand.Parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
                    myCommand.Parameters.Add("@FromClause", SqlDbType.VarChar, 1024).Value = fromClause.ToString();
                    myCommand.Parameters.Add("@SelectFields", SqlDbType.VarChar, 512).Value = "R.*";
                    myCommand.Parameters.Add("@WhereClause", SqlDbType.NVarChar, 4000).Value = whereClause.ToString();
                    myCommand.Parameters.Add("@SortField", SqlDbType.VarChar, 256).Value = "R.PrivilegeID";
                    myCommand.Parameters.Add("@SortFieldIsDesc", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@ReturnRecordCount", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@MaxRecords", SqlDbType.Int).Value = int.MaxValue;
                    myCommand.Parameters.Add("@TotalRecords", SqlDbType.Int).Direction = ParameterDirection.Output;
                    myCommand.Parameters.Add("@ReverseOrder", SqlDbType.Bit).Direction = ParameterDirection.Output;

                    List<Privilege> list = new List<Privilege>();
                    DataSet dataSet = new DataSet();
                    SqlDataAdapter da = new SqlDataAdapter(myCommand);
                    da.Fill(dataSet);

                    if (dataSet != null)
                    {
                        foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                        {
                            Privilege jshAccount = new Privilege(dataRow);
                            if (jshAccount.TranByConstructFlag)
                            {
                                list.Add(jshAccount);
                            }
                        }
                    }

                    int totalRecords = Convert.ToInt32(myCommand.Parameters["@TotalRecords"].Value);
                    bool reverseOrder = Convert.ToBoolean(myCommand.Parameters["@ReverseOrder"].Value);

                    if (reverseOrder)
                        list.Reverse();

                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = new PagingDataSet<Privilege>() { PageIndex = pageIndex, PageSize = pageSize, Records = list, TotalRecords = totalRecords };
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="priid">权限id</param>
        /// <returns></returns>
        public ResultInfo<Privilege> GetPrivilege(int priid)
        {
            ResultInfo<Privilege> result = new ResultInfo<Privilege>();
            try
            {
                string sql = string.Format("select * from privilege where privilegeid ={0}", priid);

                if (!string.IsNullOrEmpty(sql))
                {
                    DataSet dataSet = ExcuteSqlDataSet(sql);
                    if (dataSet != null && dataSet.Tables[0].Rows.Count == 1)
                    {
                        Privilege p = new Privilege(dataSet.Tables[0].Rows[0]);
                        if (p.TranByConstructFlag)
                        {
                            result.ResultNumber = ResultEnum.Success;
                            result.Obj = p;
                        }
                        else
                        {
                            result.ResultNumber = ResultEnum.Error;
                            result.Describe = "获取失败";
                        }
                    }
                }
            }
            catch (Exception e)
            {

            }
            return result;
        }

        /// <summary>
        /// 创建或更新权限信息，如果权限的id大于0就是更新，如果权限的id小于等于0就是新增
        /// </summary>
        /// <param name="privilege"></param>
        /// <returns></returns>
        public ResultInfo<int> CreateUpdatePrivilege(Privilege privilege)
        {
            ResultInfo<int> result = new ResultInfo<int>();
            try
            {
                string sql = string.Empty;
                if (privilege != null)
                {
                    if (privilege.Privilegeid > 0)
                    {
                        sql = string.Format("UPDATE Privilege SET [PrivilegeName]='{0}',[PrivilegeResource]='{1}',[createtime]=getdate() where [PrivilegeID]={2} select {2} id", privilege.Privilegename, privilege.Privilegeresource, privilege.Privilegeid);
                    }
                    else
                    {
                        string check = string.Format("select privilegeid from Privilege where privilegename='{0}'", privilege.Privilegename);
                        DataSet dt = ExcuteSqlDataSet(check);
                        if (dt != null && dt.Tables[0].Rows.Count > 0)
                        {
                            result.ResultNumber = ResultEnum.Error;
                            result.Describe = "已经存在同名权限，请重新输入";
                        }
                        else
                        {
                            sql = string.Format("insert into Privilege([PrivilegeName],[PrivilegeResource],[createtime]) values('{0}','{1}',getdate()) select @@identity id", privilege.Privilegename, privilege.Privilegeresource);
                        }
                    }
                    if (!string.IsNullOrEmpty(sql))
                    {
                        DataSet dataSet = ExcuteSqlDataSet(sql);
                        if (dataSet != null && dataSet.Tables[0].Rows.Count == 1)
                        {
                            int temp = Convert.ToInt32(dataSet.Tables[0].Rows[0]["id"]);
                            if (temp > 0)
                            {
                                result.ResultNumber = ResultEnum.Success;
                                result.Obj = temp;
                            }
                            else
                            {
                                result.ResultNumber = ResultEnum.Error;
                                result.Describe = "更新数据失败";
                            }
                        }
                    }
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = "请输入有效数据";
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 删除指定id的权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultInfo<bool> DeletePrivilege(int id)
        {
            ResultInfo<bool> result = new ResultInfo<bool>() { ResultNumber = ResultEnum.Error };
            try
            {
                string sql = string.Format("delete from Privilege where privilegeid={0}", id);
                int temp = ExcuteSql(sql);
                if (temp > 0)
                {
                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = true;
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Obj = false;
                }
            }
            catch (Exception)
            {

            }
            return result;
        }

        /// <summary>
        /// 获取所有资源名称（资源就是系统中所有的Form）
        /// </summary>
        /// <returns></returns>
        private ResultInfo<List<string>> GetAllResources()
        {
            ResultInfo<List<string>> result = new ResultInfo<List<string>>() { ResultNumber = ResultEnum.Error, Obj = new List<string>() };
            try
            {
                if(_cacheResources!=null&&_cacheResources.ResultNumber==ResultEnum.Success)
                {
                    result = _cacheResources;
                }else
                {
                    foreach (var type in this.GetType().Assembly.GetTypes())
                    {
                        if (typeof(Form).IsAssignableFrom(type))
                        {
                            try
                            {
                                using (Form form = Activator.CreateInstance(type) as Form)
                                {
                                    if (form != null && !string.IsNullOrEmpty(form.Text))
                                    {
                                        result.Obj.Add(form.Text);
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                    result.ResultNumber = ResultEnum.Success;
                    _cacheResources = result;
                }
            }
            catch (Exception e)
            {
                result.Describe = e.Message;
                result.ResultNumber = ResultEnum.Error;
                _cacheResources = result;
            }
            return result;
        }

        /// <summary>
        /// 获取所有资源名称
        /// </summary>
        /// <returns></returns>
        public ResultInfo<Dictionary<string, string>> GetAllKeyResources()
        {
            var result = new ResultInfo<Dictionary<string, string>>
            {
                ResultNumber = ResultEnum.Error,
                Obj = new Dictionary<string, string>()
            };
            try
            {
                if(_cacheDicResources!=null&&_cacheDicResources.ResultNumber==ResultEnum.Success)
                {
                    result = _cacheDicResources;
                }else
                {
                    foreach (var type in System.Reflection.Assembly.LoadFile(Application.ExecutablePath).GetTypes())
                    {
                        if (typeof(Form).IsAssignableFrom(type))
                        {
                            try
                            {
                                using (var form = Activator.CreateInstance(type) as Form)
                                {
                                    if (form != null && !string.IsNullOrEmpty(form.Name))
                                    {
                                        result.Obj.Add(form.Name, form.Text);
                                    }
                                }
                            }
                            catch
                            {
                                //throw new DataException();
                            }
                        }
                    }
                    result.ResultNumber = ResultEnum.Success;
                    _cacheDicResources = result;
                }
            }
            catch (Exception e)
            {
                result.Describe = e.Message;
                result.ResultNumber = ResultEnum.Error;
                _cacheDicResources = result;
            }
            return result;
        }

        /// <summary>
        /// 获取一个权限没有的资源
        /// </summary>
        /// <param name="priviid">权限id</param>
        /// <returns></returns>
        public ResultInfo<List<string>> GetPriviUnResources(int priviid)
        {
            ResultInfo<List<string>> result = new ResultInfo<List<string>>() { ResultNumber = ResultEnum.Error, Obj = new List<string>() };
            ResultInfo<List<string>> all = GetAllResources();
            try
            {
                if (all.ResultNumber == ResultEnum.Success)
                {
                    ResultInfo<Privilege> hpris = GetPrivilege(priviid);
                    if (hpris.ResultNumber == ResultEnum.Success && !string.IsNullOrEmpty(hpris.Obj.Privilegeresource))
                    {
                        List<string> hpristr = hpris.Obj.Privilegeresource.Split(',').ToList();
                        foreach (string r in all.Obj)
                        {
                            if (!hpristr.Contains(r))
                            {
                                result.Obj.Add(r);
                            }
                        }
                        result.ResultNumber = ResultEnum.Success;
                    }
                    else
                    {
                        result.ResultNumber = ResultEnum.Error;
                        result.Describe = hpris.Describe;
                    }
                }
            }
            catch (Exception)
            {
                result = all;
            }
            return result;
        }

        /// <summary>
        /// 获取权限已经有的资源
        /// </summary>
        /// <param name="priviid">权限id</param>
        /// <returns></returns>
        public ResultInfo<List<string>> GetPriviResources(int priviid)
        {
            var result = new ResultInfo<List<string>>() { Obj = new List<string>() };
            try
            {

                ResultInfo<Privilege> pri = GetPrivilege(priviid);
                if (pri.ResultNumber == ResultEnum.Success)
                {
                    string resources = pri.Obj.Privilegeresource;
                    if (!string.IsNullOrEmpty(resources))
                    {
                        foreach (string resource in resources.Split(','))
                        {
                            if (!string.IsNullOrEmpty(resource) && !result.Obj.Contains(resource))
                            {
                                result.Obj.Add(resource);
                            }
                        }
                        result.ResultNumber = ResultEnum.Success;
                    }
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = "没有获取到相关资源";
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取权限的资源键值对
        /// </summary>
        /// <param name="priviid"></param>
        /// <returns></returns>
        public ResultInfo<Dictionary<string,string>> GetPriviKeyResources(int priviid)
        {
            var result = new ResultInfo<Dictionary<string, string>>
            {
                ResultNumber = ResultEnum.Error,
                Obj = new Dictionary<string, string>()
            };
            try
            {
                ResultInfo<Dictionary<string, string>> allResources = GetAllKeyResources();
                if(allResources.ResultNumber==ResultEnum.Success)
                {
                    if(priviid>0)
                    {
                        ResultInfo<List<string>> hres = GetPriviResources(priviid);
                        if (hres.ResultNumber == ResultEnum.Success)
                        {
                            result.Obj = allResources.Obj.Where(o => (hres.Obj.Contains(o.Key))).ToDictionary(t => t.Key, t => t.Value);
                            result.ResultNumber = ResultEnum.Success;
                        }
                    }else
                    {
                        result = allResources;
                    }
                }
            }
            catch (Exception e)
            {
                result.Describe = e.Message;
                result.ResultNumber = ResultEnum.Error;
            }
            return result;
        }


    }
}
